package com.amsp.oa.oademo.service.impl;

import com.amsp.oa.oademo.entity.PurchaseRequest;
import com.amsp.oa.oademo.entity.PurchaseRequestItem;
import com.amsp.oa.oademo.mapper.PurchaseRequestItemMapper;
import com.amsp.oa.oademo.mapper.PurchaseRequestMapper;
import com.amsp.oa.oademo.service.PurchaseRequestService;
import com.amsp.oa.oademo.vo.PurchaseRequestItemVO;
import com.amsp.oa.oademo.vo.PurchaseRequestVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 申购单Service实现类
 */
@Service
public class PurchaseRequestServiceImpl extends ServiceImpl<PurchaseRequestMapper, PurchaseRequest>
        implements PurchaseRequestService {

    @Resource
    private PurchaseRequestItemMapper purchaseRequestItemMapper;

    @Override
    public IPage<PurchaseRequest> getList(Integer page, Integer size, String month, String department) {
        Page<PurchaseRequest> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<PurchaseRequest> queryWrapper = new LambdaQueryWrapper<>();

        // 如果有月份条件，按月份筛选
        if (StringUtils.isNotBlank(month)) {
            LocalDate startDate = LocalDate.parse(month + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate endDate = startDate.plusMonths(1).minusDays(1);
            queryWrapper.between(PurchaseRequest::getRequestDate, startDate, endDate);
        }

        // 如果有部门条件，按部门筛选
        if (StringUtils.isNotBlank(department)) {
            queryWrapper.like(PurchaseRequest::getDepartment, department);
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(PurchaseRequest::getCreateTime);

        return page(pageParam, queryWrapper);
    }

    @Override
    public PurchaseRequestVO getDetail(Long id) {
        // 查询主表信息
        PurchaseRequest purchaseRequest = getById(id);
        if (purchaseRequest == null) {
            return null;
        }

        // 查询明细表信息
        LambdaQueryWrapper<PurchaseRequestItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PurchaseRequestItem::getRequestId, id);
        List<PurchaseRequestItem> itemList = purchaseRequestItemMapper.selectList(queryWrapper);

        // 转换为VO对象
        PurchaseRequestVO vo = new PurchaseRequestVO();
        vo.setId(purchaseRequest.getId());
        vo.setNo(purchaseRequest.getRequestNo());
        vo.setDepartment(purchaseRequest.getDepartment());
        vo.setDate(purchaseRequest.getRequestDate() != null ? purchaseRequest.getRequestDate().toString() : null);
        vo.setApprover(purchaseRequest.getApprover());
        vo.setReviewer(purchaseRequest.getReviewer());
        vo.setConfirmator(purchaseRequest.getConfirmator());
        vo.setFormMaker(purchaseRequest.getFormMaker());

        // 转换明细列表
        List<PurchaseRequestItemVO> itemVOList = new ArrayList<>();
        if (itemList != null && !itemList.isEmpty()) {
            itemVOList = itemList.stream().map(item -> {
                PurchaseRequestItemVO itemVO = new PurchaseRequestItemVO();
                BeanUtils.copyProperties(item, itemVO);
                itemVO.setNeededDate(item.getNeededDate() != null ? item.getNeededDate().toString() : null);
                itemVO.setReplyDate(item.getReplyDate() != null ? item.getReplyDate().toString() : null);
                itemVO.setIsChecked(false); // 默认未选中
                return itemVO;
            }).collect(Collectors.toList());
        }
        vo.setItemList(itemVOList);

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(PurchaseRequestVO purchaseRequestVO) {
        if (purchaseRequestVO == null) {
            return false;
        }

        // 转换为实体对象
        PurchaseRequest purchaseRequest = new PurchaseRequest();
        purchaseRequest.setId(purchaseRequestVO.getId());
        purchaseRequest.setRequestNo(purchaseRequestVO.getNo());
        purchaseRequest.setDepartment(purchaseRequestVO.getDepartment());
        if (StringUtils.isNotBlank(purchaseRequestVO.getDate())) {
            purchaseRequest.setRequestDate(LocalDate.parse(purchaseRequestVO.getDate()));
        }
        purchaseRequest.setApprover(purchaseRequestVO.getApprover());
        purchaseRequest.setReviewer(purchaseRequestVO.getReviewer());
        purchaseRequest.setConfirmator(purchaseRequestVO.getConfirmator());
        purchaseRequest.setFormMaker(purchaseRequestVO.getFormMaker());

        // 保存主表
        boolean result = saveOrUpdate(purchaseRequest);
        if (!result) {
            return false;
        }

        // 获取主表ID
        Long requestId = purchaseRequest.getId();

        // 如果是更新操作，先删除原有明细
        if (purchaseRequestVO.getId() != null) {
            LambdaQueryWrapper<PurchaseRequestItem> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PurchaseRequestItem::getRequestId, requestId);
            purchaseRequestItemMapper.delete(queryWrapper);
        }

        // 保存明细表
        List<PurchaseRequestItemVO> itemVOList = purchaseRequestVO.getItemList();
        if (itemVOList != null && !itemVOList.isEmpty()) {
            for (PurchaseRequestItemVO itemVO : itemVOList) {
                // 过滤掉空的明细项
                if (StringUtils.isBlank(itemVO.getProductName())) {
                    continue;
                }

                PurchaseRequestItem item = new PurchaseRequestItem();
                BeanUtils.copyProperties(itemVO, item);
                item.setId(null); // 确保是新增
                item.setRequestId(requestId);

                // 转换日期
                if (StringUtils.isNotBlank(itemVO.getNeededDate())) {
                    item.setNeededDate(LocalDate.parse(itemVO.getNeededDate()));
                }
                if (StringUtils.isNotBlank(itemVO.getReplyDate())) {
                    item.setReplyDate(LocalDate.parse(itemVO.getReplyDate()));
                }

                purchaseRequestItemMapper.insert(item);
            }
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        if (id == null) {
            return false;
        }

        // 删除明细表
        LambdaQueryWrapper<PurchaseRequestItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PurchaseRequestItem::getRequestId, id);
        purchaseRequestItemMapper.delete(queryWrapper);

        // 删除主表
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        // 批量删除明细表
        LambdaQueryWrapper<PurchaseRequestItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PurchaseRequestItem::getRequestId, ids);
        purchaseRequestItemMapper.delete(queryWrapper);

        // 批量删除主表
        return removeByIds(ids);
    }
}